/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.anjiplus.template.gaea.generator.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.anjiplus.template.gaea.generator.domain.GenConfig;
import com.anjiplus.template.gaea.generator.project.dao.entity.Project;
import com.anjiplus.template.gaea.generator.project.service.ProjectService;
import com.anjiplus.template.gaea.generator.repository.GenConfigRepository;
import com.anjiplus.template.gaea.generator.service.GenConfigService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import com.anjiplus.template.gaea.generator.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Zheng Jie
 * @date 2019-01-14
 */
@Service
@RequiredArgsConstructor
@Slf4j
@RefreshScope
@ConditionalOnExpression("${generator.enabled:false}")
public class GenConfigServiceImpl implements GenConfigService {

    private final GenConfigRepository genConfigRepository;

    @Value("${generator.workspace}")
    String workspace;

    @Value("${generator.templatePath:template}")
    String templatePath;

    @Autowired
    private ProjectService projectService;

    @Override
    public GenConfig find(String project, String tableName) {
        //GenConfig genConfig = null;
        //genconfig = genConfigRepository.findByTableName(tableName);
        Map m = new HashMap();
        m.put("table_Name",tableName);
        m.put("project",project);
        List<GenConfig> genConfigs = genConfigRepository.selectByMap(m);
        if(genConfigs == null || genConfigs.size() ==0){
            //代码生成 包路径默认配置，可以在页面修改
            String sub = project;
            if(project.contains("-")) {
                sub = project.replaceAll("-",".");
            }
            String t = StringUtils.toCamelCase(tableName);

            GenConfig cfg = new GenConfig(tableName);
            //cfg.setApiAlias("领域模型-功能说明");//手工维护
            cfg.setAuthor("dev-user");
            cfg.setPack("com.anjiplus.".concat(sub).concat(".business.modules.").concat(t));
            cfg.setPack(cfg.getPack().toLowerCase());
            cfg.setModuleName(project.concat("-business"));
            cfg.setProject(project);
            Project proj = projectService.selectOne("code",project);
            cfg.setProjectRoot(proj.getProjectRoot());
            cfg.setCover(false);
            cfg.setPath("/"+project.concat("-ui/src/views/").concat(t));
            cfg.setWorkspace(workspace);
            cfg.setPrefix("t_");
            return cfg;
        }
        genConfigs.get(0).setWorkspace(workspace);
        return genConfigs.get(0);
    }

    @Override
    public GenConfig update(String tableName, GenConfig genConfig) {
        /*String separator = File.separator;
        String[] paths;
        String symbol = "\\";
        if (symbol.equals(separator)) {
            paths = genConfig.getPath().split("\\\\");
        } else {
            paths = genConfig.getPath().split(File.separator);
        }
        StringBuilder api = new StringBuilder();
        for (String path : paths) {
            api.append(path);
            api.append(separator);
            if ("src".equals(path)) {
                api.append("api");
                break;
            }
        }*/
        genConfig.setApiPath(genConfig.getPath().substring(0,genConfig.getPath().indexOf("src/")+3)+"/api/");
        LambdaQueryWrapper<GenConfig> w = Wrappers.lambdaQuery();
        w.eq(GenConfig::getTableName, tableName)
                .and(q->q.eq(GenConfig::getProject,genConfig.getProject()));
        GenConfig c = genConfigRepository.selectOne(w);
        if(c!=null) {
            genConfig.setId(c.getId());
            genConfigRepository.updateById(genConfig);
        }else {
            genConfigRepository.insert(genConfig);
        }
        GeneratorUtilServiceImpl.TEMPLATE_PATH = templatePath;
        log.info("gen-template:{}",templatePath);
        return genConfig;
    }
}
